# _*_ coding:utf-8 _*_
# @Time  : 2022.10.17
# @Author: zizlee
import datetime
import json
import time

import numpy as np
import requests
import pandas as pd
from urllib3 import disable_warnings
disable_warnings()

HOST = 'https://210.13.218.130:9000/v1/'

VARIETY_BLOCK = {
    'A': '农产品',
    'AG': '黑色系',
    'AL': '黑色系',
    'AP': '农产品',
    'AU': '黑色系',
    'BU': '化工品',
    'C': '农产品',
    'CF': '农产品',
    'CJ': '农产品',
    'CS': '农产品',
    'CU': '黑色系',
    'CY': '农产品',
    'EB': '化工品',
    'EG': '化工品',
    'FG': '化工品',
    'FU': '化工品',
    'HC': '黑色系',
    'I': '黑色系',
    'J': '黑色系',
    'JD': '农产品',
    'JM': '黑色系',
    'L': '化工品',
    'LH': '农产品',
    'LU': '化工品',
    'M': '农产品',
    'MA': '化工品',
    'NI': '黑色系',
    'NR': '化工品',
    'OI': '农产品',
    'P': '农产品',
    'PB': '黑色系',
    'PF': '化工品',
    'PG': '化工品',
    'PK': '农产品',
    'PP': '化工品',
    'RB': '黑色系',
    'RM': '农产品',
    'RS': '农产品',
    'RU': '化工品',
    'SA': '化工品',
    'SC': '化工品',
    'SF': '黑色系',
    'SM': '黑色系',
    'SN': '黑色系',
    'SP': '化工品',
    'SR': '农产品',
    'SS': '黑色系',
    'TA': '化工品',
    'UR': '化工品',
    'V': '化工品',
    'Y': '农产品',
    'ZC': '黑色系',
    'ZN': '黑色系',
}


def read_configs():
    with open('每日库存Configs.json', 'r', encoding='utf8') as cf:
        configs = json.load(cf)
    return configs


def get_rdb_data(stock_item):
    r = requests.post(HOST + 'datalib/indexAis/formulaData/', verify=False,
                      json={'formula': stock_item['formula'], 'na_fill': 0})
    resp_data = r.json()['data']
    return resp_data['data']


def handle_stock_value(stock_item, data_list):
    df = pd.DataFrame(data_list)
    df.sort_values(by='datadate', inplace=True)
    # 小于设定日期的数据
    df = df[df['datadate'] <= STOCK_DATE]
    df['datavalue'] = df['datavalue'].apply(lambda x: round(x/stock_item['unit_divisor'], 2))
    value_start = df['datadate'].min()
    current_date = datetime.datetime.strptime(df['datadate'].max(), '%Y-%m-%d')
    one_year_ago = (current_date - datetime.timedelta(days=360)).strftime('%Y-%m-%d')  # 1年前
    two_year_ago = (current_date - datetime.timedelta(days=720)).strftime('%Y-%m-%d')  # 前年

    stock_date = current_date.strftime('%Y-%m-%d')
    stock_value = df.tail(1)['datavalue'].values[0]

    # 环比
    last_five_df = df.tail(5).copy()
    last_five_df['diff_value'] = last_five_df['datavalue'] - last_five_df['datavalue'].shift(1)
    last_five_df['diff_rate'] = (last_five_df['diff_value'] * 100 / last_five_df['datavalue'].shift(1)).round(2)
    ring_rate = last_five_df.tail(1)['diff_rate'].values[0]
    if pd.isnull(ring_rate):
        ring_rate = 999999
    if np.isinf(ring_rate):
        ring_rate = 100

    # 去年同比(小于等于一年前的最后一个数值)
    year_values1 = df[(df['datadate'] <= one_year_ago)]['datavalue'].values
    if len(year_values1) < 1:
        same_rate1 = 999999
    else:
        same_value1 = year_values1[-1]
        if same_value1 == 0 and stock_value == 0:
            same_rate1 = 999999
        else:
            same_rate1 = round((stock_value - same_value1) * 100 / same_value1, 2) if same_value1 != 0 else 100
    # 前年同比
    year_values2 = df[(df['datadate'] <= two_year_ago)]['datavalue'].values
    if len(year_values2) < 1:
        same_rate2 = 999999
    else:
        same_value2 = year_values2[-1]
        if same_value2 == 0 and stock_value == 0:
            same_rate2 = 999999
        else:
            same_rate2 = round((stock_value - same_value2) * 100 / same_value2, 2) if same_value2 != 0 else 100

    # 近1月高点
    highest1 = df[df['datadate'] >= (current_date - datetime.timedelta(days=30)).strftime('%Y-%m-%d')]['datavalue'].max()
    # 近3月高点
    highest2 = df[df['datadate'] >= (current_date - datetime.timedelta(days=90)).strftime('%Y-%m-%d')]['datavalue'].max()
    # 近6月高点
    highest3 = df[df['datadate'] >= (current_date - datetime.timedelta(days=180)).strftime('%Y-%m-%d')]['datavalue'].max()
    # 历史高点
    highest0 = df['datavalue'].max()
    # 历史低点
    lowest0 = df['datavalue'].min()
    # 计算当前水平点
    c_level = round((stock_value - lowest0) * 100 / (highest0 - lowest0), 2) if (highest0 - lowest0) != 0 else 100
    stock_unit = stock_item.get('fact_unit', stock_item['unit'])

    return {
        'stock_date': STOCK_DATE,
        'rdb_id': stock_item['rdb_id'],
        'block_name': stock_item['block'],
        'variety_en': stock_item['variety_en'],
        'variety_name': stock_item['variety_name'],
        'stock_name': stock_item['stock_name'],
        'stock_unit': stock_unit,
        'frequency': stock_item['frequency'],
        'date_latest': stock_date,
        'stock_latest': stock_value,
        'ring_rate': ring_rate,
        'same_rate1': same_rate1,
        'same_rate2': same_rate2,
        'highest1': highest1,
        'highest2': highest2,
        'highest3': highest3,
        'highest0': highest0,
        'lowest0': lowest0,
        'c_level': c_level,
        'is_fine': stock_item['is_fine'],
        'value_start': value_start
    }


def save_stock_to_server(data):
    r = requests.post('https://210.13.218.130:9000/v1/' + 'datan/stock/', json=data, verify=False)
    # r = requests.post('http://127.0.0.1:8000/v1/' + 'datan/stock/', json=data, verify=False)
    print(r.json())


if __name__ == '__main__':
    # STOCK_DATE = (datetime.datetime.today() - datetime.timedelta(days=22)).strftime('%Y%m%d')
    for dt in ['20231030', '20231031', '20231101', '20231104', '20231105']:
        STOCK_DATE = dt
        print('处理库存日期:', STOCK_DATE)
        stock_list = read_configs()
        value_list = []
        for item in stock_list:
            stock_data = get_rdb_data(item)
            stock_values = handle_stock_value(item, stock_data)
            value_list.append(stock_values)
            print('RDB={},{} 库存数据处理完成!'.format(item['rdb_id'], item['stock_name']))
            time.sleep(0.5)
        with open('bak.json', 'w', encoding='utf8') as f:
            json.dump(value_list, f, indent=2, ensure_ascii=False)
        save_stock_to_server(value_list)

    # with open('bak.json', 'r', encoding='utf8') as f:
    #     c = json.load(f)
    #
    # print(np.isinf(np.Infinity))
    # save_stock_to_server(c)
